#define DOHOME_LOG_LVL          DOHOME_LOG_LVL_ERROR
#define DOHOME_LOG_TAG          "hal_timer"

#include "dohome_hal_timer.h"

#include "dohome_log.h"


typedef struct _timer_ctx{
	struct _timer_ctx *next;
	DOHOME_UINT8_T id;
	DOHOME_UINT8_T start;
	DOHOME_UINT32_T period_us;
	DOHOME_UINT32_T repeat;
	dohome_hal_timer_cbfunc_t cb;
	void *arg;
	DOHOME_UINT32_T calc_us;
}_timer_ctx_t;

_timer_ctx_t *ctx_head = NULL;


static DOHOME_UINT8_T timer_id_max = 0;

static void ms_timer_cb(void *arg){
	_timer_ctx_t *node_f = NULL;

	if(ctx_head){
        for (node_f = ctx_head; node_f != NULL; node_f = node_f->next) {
			node_f->calc_us+=1000;
            if (node_f->start && node_f->calc_us == node_f->period_us) {
				node_f->cb(node_f->arg);
				node_f->calc_us = 0;
				if(!node_f->repeat){
					node_f->start = 0;
				}
			}
        }
    }
}

dohome_op_ret dohome_hal_timer_init(DOHOME_UINT8_T *timer_id, DOHOME_UINT32_T ms, DOHOME_UINT32_T repeat, dohome_hal_timer_cbfunc_t cbfunc)
{
	
	return OPRT_OK;
}

dohome_op_ret dohome_hal_timer_us_init(DOHOME_UINT8_T *timer_id, DOHOME_UINT32_T us, DOHOME_UINT32_T repeat, dohome_hal_timer_cbfunc_t cbfunc)
{
	return OPRT_COM_ERROR;
}

dohome_op_ret dohome_hal_timer_start(DOHOME_UINT8_T timer_id)
{
	_timer_ctx_t *node_f = NULL;
	dohome_op_ret ret = OPRT_COM_ERROR;

	if(ctx_head){
        for (node_f = ctx_head; node_f != NULL; node_f = node_f->next) {
            if (node_f->id == timer_id) {
				node_f->start = 1;
				return OPRT_OK;
			}
        }
    }
	return ret;
}

dohome_op_ret dohome_hal_timer_stop(DOHOME_UINT8_T timer_id)
{
	_timer_ctx_t *node_f = NULL;
	dohome_op_ret ret = OPRT_COM_ERROR;

	if(ctx_head){
        for (node_f = ctx_head; node_f != NULL; node_f = node_f->next) {
            if (node_f->id == timer_id) {
				node_f->start = 0;
				return OPRT_OK;
			}
        }
    }
	return ret;
}